//
//  UINavigationController+DCBackGesture.m
//

#import "UINavigationController+DCBackGesture.h"
#import <objc/runtime.h>

static const char *assoKeyPanGesture="__dcpanges";
static const char *assoKeyStartPanGesture="__dcstartpan";
static const char *assoKeyEnableGesture="__dcenabpan";


@implementation UINavigationController (DCBackGesture)


/**属性enableBackGesture的 setter && getter*/
- (BOOL)enableBackGesture{
    NSNumber *enableGestureNum = objc_getAssociatedObject(self, assoKeyEnableGesture);
    if (enableGestureNum) {
        return [enableGestureNum boolValue];
    }
    return false;
}
- (void)setEnableBackGesture:(BOOL)enableBackGesture{
    NSNumber *enableGestureNum = [NSNumber numberWithBool:enableBackGesture];
    objc_setAssociatedObject(self, assoKeyEnableGesture, enableGestureNum, OBJC_ASSOCIATION_RETAIN);
    if (enableBackGesture) {
        [self.view addGestureRecognizer:[self panGestureRecognizer]];
    }else{
        [self.view removeGestureRecognizer:[self panGestureRecognizer]];
    }
    
}


/**初始化手势*/
- (UIPanGestureRecognizer *)panGestureRecognizer{
    UIPanGestureRecognizer *panGestureRecognizer = objc_getAssociatedObject(self, assoKeyPanGesture);
    if (!panGestureRecognizer) {
        panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panToBack:)];
        [panGestureRecognizer setDelegate:self];
        objc_setAssociatedObject(self, assoKeyPanGesture, panGestureRecognizer, OBJC_ASSOCIATION_RETAIN);
    }
    return panGestureRecognizer;
}

/**startPoint的 setter && getter*/
- (CGPoint)startPanPoint{
    NSValue *startPanPointValue = objc_getAssociatedObject(self, assoKeyStartPanGesture);
    if (!startPanPointValue) {
        return CGPointZero;
    }
    return [startPanPointValue CGPointValue];
}

- (void)setStartPanPoint:(CGPoint)point{
    NSValue *startPanPointValue = [NSValue valueWithCGPoint:point];
    objc_setAssociatedObject(self, assoKeyStartPanGesture, startPanPointValue, OBJC_ASSOCIATION_RETAIN);
}


/**手势绑定方法*/
- (void)panToBack:(UIPanGestureRecognizer *)pan{
    UIView *currentView = self.topViewController.view;
    
    //判断滑动手势开始 
    if (self.panGestureRecognizer.state == UIGestureRecognizerStateBegan) {
        [self setStartPanPoint:currentView.frame.origin];
        CGPoint velocity = [pan velocityInView:self.view];
        if (velocity.x != 0) {
            [self willShowPreViewController];
        }
        return;
    }
    
    
    //根据视图偏移量判断向左滑或者向右滑
    CGPoint currentPosition = [pan translationInView:self.view];
    CGFloat offsetX = [self startPanPoint].x + currentPosition.x;
    CGFloat offsetY = [self startPanPoint].y + currentPosition.y;
    if (offsetX > 0) {
        //向左滑
//        if (true) {
//            offsetX = offsetX > self.view.frame.size.width ? self.view.frame.size.width : offsetX;
//        }else{
//            offsetX = 0;
//        }
    }else if (offsetX<0){
        //向右滑
        if (currentView.frame.origin.x > 0) {
            offsetX = offsetX < -self.view.frame.size.width ? -self.view.frame.size.width : offsetX;
        }else{
            offsetX = 0;
        }
    }
    
    
    if (!CGPointEqualToPoint(CGPointMake(offsetX, offsetY), currentView.frame.origin)) {
        [self layoutCurrentViewWithOffset:UIOffsetMake(offsetX, offsetY)];
    }
    
    //判断滑动手势结束   页面的隐藏或者显示
    if (self.panGestureRecognizer.state==UIGestureRecognizerStateEnded) {
        if (currentView.frame.origin.x == 0) {
            
        }else{
            if (currentView.frame.origin.x < BackGestureOffsetXToBack) {
                [self hidePreViewController];
            }else{
                [self showPreViewController];
            }
        }
    }
}


/**将要显示前一个页面的时候*/
- (void)willShowPreViewController{
    NSInteger count = self.viewControllers.count;
    if (count > 1) {
        UIViewController *currentVC = [self topViewController];
        UIViewController *preVC = [self.viewControllers objectAtIndex:count - 2];
        [currentVC.view.superview insertSubview:preVC.view belowSubview:currentVC.view];
    }
}

/**显示前一个页面*/
- (void)showPreViewController{
    NSInteger count = self.viewControllers.count;
    if (count>1) {
        UIView *currentView = self.topViewController.view;
        NSTimeInterval animatedTime = 0;
        animatedTime = ABS(self.view.frame.size.width - currentView.frame.origin.x) / self.view.frame.size.width * 0.35;
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView animateWithDuration:animatedTime animations:^{
            [self layoutCurrentViewWithOffset:UIOffsetMake(self.view.frame.size.width, 0)];
        } completion:^(BOOL finished) {
            [self popViewControllerAnimated:false];
        }];
    }
}

/**隐藏前一个页面*/
- (void)hidePreViewController{
    NSInteger count = self.viewControllers.count;
    if (count>1) {
        UIView *currentView = self.topViewController.view;
        UIViewController *preVC = [self.viewControllers objectAtIndex:count - 2];
        NSTimeInterval animatedTime = 0;
        animatedTime = ABS(self.view.frame.size.width - currentView.frame.origin.x) / self.view.frame.size.width * 0.35;
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView animateWithDuration:animatedTime animations:^{
            [self layoutCurrentViewWithOffset:UIOffsetMake(0, 0)];
        } completion:^(BOOL finished) {
            [preVC.view removeFromSuperview];
        }];
    }
    
}

/**当前视图的偏移量*/
- (void)layoutCurrentViewWithOffset:(UIOffset)offset{
    NSInteger count = self.viewControllers.count;
    if (count > 1) {
        UIViewController *currentVC = [self topViewController];
        UIViewController *preVC = [self.viewControllers objectAtIndex:count - 2];
        [currentVC.view setFrame:CGRectMake(offset.horizontal, self.view.bounds.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
        [preVC.view setFrame:CGRectMake(offset.horizontal/2 - self.view.frame.size.width/2, self.view.bounds.origin.y,self.view.frame.size.width, self.view.frame.size.height)];
    }
}

/**手势？？？开始？？？*/
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (gestureRecognizer) {
        return false;
    }
    return true;
}

@end
